import json

from django import http
from django.conf import settings
from django.contrib.auth import login
from django.shortcuts import render
from django.views import View

from QQLoginTool.QQtool import OAuthQQ
from .models import OAuthQQUser
from meiduo_mall.utils.secret import SecretOauth


# 判断是否绑定 openid
from ..users.models import User


def is_bind_openid(request, openid):
    try:
        #  去QQ的用户表 中查询 有没有这个openid
        oauth_qq = OAuthQQUser.objects.get(openid=openid)
    except OAuthQQUser.DoesNotExist:
        # 没有 绑定 openid
        # 后端 需要 把 加密过的 openid 传递给 绑定页面  的前端
        secret_openid = SecretOauth().dumps({'openid':openid})
        access_token = secret_openid
        return http.JsonResponse({'code': 300, 'errmsg': '未绑定', 'access_token': access_token})
    else:
        # 绑定 openid
        user = oauth_qq.user
        # 1. 保持登录状态 login()
        login(request, user)
        # 2.设置cookie username
        response = http.JsonResponse({'code': 0, 'errmsg': '成功!'})
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)
        # 3.返回响应 JSON code:0
        return response


# 2.code-token-openid
class QQUserView(View):
    """http://www.meiduo.site:8000/oauth_callback/
    ?code=AE263F12675FA79185B54870D79730A7&state=%2F"""

    def get(self, request):
        # 1.解析参数
        code = request.GET.get('code')
        # 2.校验
        if not code:
            return http.JsonResponse({'code': 400, 'errmsg': '缺少code'})

        # 3.美多 后台 认证 QQ 的身份
        oauth = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state=None
        )

        # 4. code-->token
        token = oauth.get_access_token(code)
        # 5. token-->openid
        openid = oauth.get_open_id(token)

        # 判断是否绑定 openid
        response = is_bind_openid(request, openid)

        # 6.返回响应
        return response

    def post(self, request):
        # 1.解析参数 json
        data_dict = json.loads(request.body.decode())
        mobile = data_dict.get('mobile')
        password = data_dict.get('password')
        sms_code_client = data_dict.get('sms_code')
        access_token = data_dict.get('access_token') #openid

        # 2.校验参数 判空 判正则 短信验证码

        # 3.判断openid 是否有值 -- 解密 前端给后台 的加密 openid
        openid = SecretOauth().loads(access_token).get('openid')

        if not openid:
            return http.JsonResponse({'code': 400, 'errmsg': 'openid为空!'})

        # 4.判断mobile 的用户是否存在
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            # 新用户
            print(e)
            user = User.objects.create_user(username=mobile, mobile=mobile, password=password)
        else:
            # 判断密码是否正确
            if not user.check_password(password):
                return http.JsonResponse({'code': 400, 'errmsg': '密码错误!'})

        # 5.绑定openid 入库
        try:
             OAuthQQUser.objects.create(user=user, openid=access_token)
        except Exception as e:
            print(e)

        # 6.保持登录状态 设置cookie
        # 1. 保持登录状态 login()
        login(request, user)
        # 2.设置cookie username
        response = http.JsonResponse({'code': 0, 'errmsg': '绑定成功!'})
        response.set_cookie('username', user.username, max_age=3600 * 24 * 14)
        # 3.返回响应 JSON code:0
        return response

# 1.获取 qq_login_url
class QQURLView(View):
    def get(self, request):
        # 1.美多 后台 认证 QQ 的身份
        oauth = OAuthQQ(
            client_id=settings.QQ_CLIENT_ID,
            client_secret=settings.QQ_CLIENT_SECRET,
            redirect_uri=settings.QQ_REDIRECT_URI,
            state=None
        )

        # 2.获取 qq 登录网址
        login_qq_url = oauth.get_qq_url()

        # 3.返回给前端 login_url
        return http.JsonResponse({'code': 0, 'errmsg': 'qq网址', 'login_url': login_qq_url})
